﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Data.Common;
using Data.Enum;
using Data.Model;
using Data.ViewModel;
using DataAccess.AccountManage;
using DataAccess.BikeManage.logical;
using Ninject;
using WinForm.Helper;

namespace WinForm.UserManage
{
    public partial class FrmUserList : Form
    {
        private static readonly IKernel Kernel = new StandardKernel(new DbModule());
        private readonly IAccount _account = Kernel.Get<IAccount>();

        public FrmUserList()
        {
            InitializeComponent();

            this.dataGridViewX1.DataError += delegate(object sender, DataGridViewDataErrorEventArgs e) { };
        }

        /// <summary>
        /// 更新列表控件
        /// </summary>
        private void RefreshData()
        {
            string errorMessage = string.Empty;
            try
            {
                ResultInfo<PagingDataSet<jsh_account>> jshaccount = _account.GetAccounts(xPagingBar1.PageIndex, xPagingBar1.PageSize, txtUserName.Text,
                                                                                          txtIdCardNo.Text,
                                                                                          txtCpuId.Text);
                if (jshaccount.ResultNumber == ResultEnum.Success)
                {
                    xPagingBar1.PageIndex = jshaccount.Obj.PageIndex;
                    xPagingBar1.PageSize = jshaccount.Obj.PageSize;
                    xPagingBar1.TotalRecordCount = jshaccount.Obj.TotalRecords;
                    xPagingBar1.Bind();

                    try
                    {
                        int searil = 0;
                        List<AccountView> accounts = new List<AccountView>();
                        foreach (jsh_account a in jshaccount.Obj.Records)
                        {
                            searil++;
                            accounts.Add(new AccountView()
                                             {
                                                 BeginDate = Converts.ConvertToNormalDate(a.khdate),
                                                 CurrentMoney = a.balance,
                                                 IdCardType = a.zzlx,
                                                 IdNo = a.zzhm,
                                                 Phone = (string.IsNullOrEmpty(a.telephone) ? a.mobile : a.telephone),
                                                 Sex = a.sex,
                                                 UserName = a.username,
                                                 ValideDate = Converts.ConvertToNormalDate(a.validate),
                                                 Serial = searil,
                                                 Id = a.id,
                                                 Status = a.status
                                             });
                        }
                        dataGridViewX1.DataSource = accounts;
                    }
                    catch (Exception)
                    {
                        dataGridViewX1.DataSource = jshaccount.Obj.Records;
                    }

                }
                else
                {
                    errorMessage = errorMessage + jshaccount.Describe;
                }
            }
            catch (Exception e)
            {
                errorMessage = errorMessage + e.Message;
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        /// <summary>
        /// 从cpu卡获取cpuid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bnGetCpuid_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            Zq58Logical zq58Logical = new Zq58Logical();
            ResultInfo<CpuAccount> cpuAccount = zq58Logical.ReadAccountInfo();
            if (cpuAccount.ResultNumber == ResultEnum.Success)
            {
                txtCpuId.Text = cpuAccount.Obj.CpuCardId;
            }
            else
            {
                MyMessageBox.ShowMessageBoxError(cpuAccount.Describe);
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        private void FrmUserList_Load(object sender, EventArgs e)
        {
            //分页控件初始化
            xPagingBar1.PageIndex = 1;
            xPagingBar1.PageSize = 20;
            xPagingBar1.xRefresh += RefreshData;
            //RefreshData();
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tnQuery_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            if (string.IsNullOrEmpty(txtUserName.Text) && string.IsNullOrEmpty(txtCpuId.Text) && string.IsNullOrEmpty(txtIdCardNo.Text))
            {
                Zq58Logical zq58Logical = new Zq58Logical();
                ResultInfo<CpuAccount> account = zq58Logical.ReadAccountInfo();
                if (account.ResultNumber == ResultEnum.Success)
                {
                    txtUserName.Text = account.Obj.DisplayName;
                    txtCpuId.Text = account.Obj.CpuCardId;
                    txtIdCardNo.Text = account.Obj.IdCardNo;
                    RefreshData();
                }
                else
                {
                    errorMessage = errorMessage + "请输入至少一个查询参数,或者将用户卡放在读卡器上";
                }
            }
            else
            {
                RefreshData();
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        /// <summary>
        /// 选择开户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Open_Click(object sender, EventArgs e)
        {
            UpdateAccountStatus(CpuCardStatus.Open);
        }

        /// <summary>
        /// 更新账户状态
        /// </summary>
        /// <param name="status"></param>
        private void UpdateAccountStatus(string status)
        {
            string errorMessage = string.Empty;
            try
            {

                if (string.IsNullOrEmpty(status))
                {
                    errorMessage = errorMessage + "请选择需要更改的类型";
                }
                else
                {
                    if (dataGridViewX1.SelectedRows.Count != 1)
                    {
                        errorMessage = errorMessage + "只能选择一条数据进行操作";
                    }
                    else
                    {

                        //跟新用户卡信息
                        Zq58Logical zq58Logical = new Zq58Logical();
                        ResultInfo<CpuAccount> cpuac = zq58Logical.ReadAccountInfo();
                        if (cpuac.ResultNumber == ResultEnum.Success)
                        {
                            string oldstatus = cpuac.Obj.CpuCardStatus;
                            cpuac.Obj.CpuCardStatus = status;
                            ResultInfo<byte[]> wa = zq58Logical.WriteAccountInfo(cpuac.Obj);

                            if (wa.ResultNumber == ResultEnum.Success)
                            {
                                long accountid = Convert.ToInt64(dataGridViewX1.SelectedRows[0].Cells["id"].Value);
                                ResultInfo<bool> us = _account.UpdateAccountStatus(accountid, status);
                                if (us.ResultNumber == ResultEnum.Success)
                                {
                                    //如果是注销用户则把用户卡的时间也该一下
                                    if(status==CpuCardStatus.Logout)
                                    {
                                        ResultInfo<BorrowBike> cpub = zq58Logical.ReadBorrowBikeInfo();
                                        cpub.Obj.EndAccountDate = "19000101";
                                        zq58Logical.WriteBorrowBikeInfo(cpub.Obj);

                                        ResultInfo<decimal> money = zq58Logical.QueryPurse();
                                        if(money.ResultNumber==ResultEnum.Success)
                                        {
                                            zq58Logical.CostMoney(money.Obj);
                                        }
                                    }

                                    RefreshData();
                                    errorMessage = "更新成功";
                                }
                                else
                                {
                                    cpuac.Obj.CpuCardStatus = oldstatus;
                                    zq58Logical.WriteAccountInfo(cpuac.Obj);
                                    errorMessage = errorMessage + us.Describe;
                                }
                            }
                            else
                            {
                                cpuac.Obj.CpuCardStatus = oldstatus;
                                zq58Logical.WriteAccountInfo(cpuac.Obj);
                                errorMessage += wa.Describe;
                            }
                        }
                        else
                        {
                            errorMessage += cpuac.Describe;
                        }
                    }
                }
            }
            catch (Exception e1)
            {
                errorMessage = errorMessage + e1.Message;
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        /// <summary>
        /// datagridview控件右键选中一行，并且显示弹出菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewX1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Right)
                {
                    if (e.RowIndex >= 0)
                    {
                        dataGridViewX1.ClearSelection();
                        dataGridViewX1.Rows[e.RowIndex].Selected = true;
                        dataGridViewX1.CurrentCell = dataGridViewX1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                        this.contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
                    }
                }
            }
            catch (Exception)
            {

            }


        }

        /// <summary>
        /// 挂失
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Loss_Click(object sender, EventArgs e)
        {
            UpdateAccountStatus(CpuCardStatus.Loss);
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Logout_Click(object sender, EventArgs e)
        {
            UpdateAccountStatus(CpuCardStatus.Logout);
        }

        /// <summary>
        /// 黑名单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Black_Click(object sender, EventArgs e)
        {
            UpdateAccountStatus(CpuCardStatus.Black);
        }

        /// <summary>
        /// 挂失
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX1_Click(object sender, EventArgs e)
        {
            UpdateAccountStatus(CpuCardStatus.Loss);
        }

        /// <summary>
        /// 解挂
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX2_Click(object sender, EventArgs e)
        {
            UpdateAccountStatus(CpuCardStatus.Open);
        }

        /// <summary>
        /// 黑名单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX3_Click(object sender, EventArgs e)
        {
            UpdateAccountStatus(CpuCardStatus.Black);
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX4_Click(object sender, EventArgs e)
        {
            UpdateAccountStatus(CpuCardStatus.Logout);
        }
    }
}
